package systemlog

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func NewAsyncFileLogger(filePath string) (*zap.Logger, error) {
	// 如果 filePath 为空，则使用默认的文件名格式
	if filePath == "" {
		now := time.Now()
		filePath = filepath.Join("runtime/logs", fmt.Sprintf("%d/%02d/%02d.log", now.Year(), now.Month(), now.Day()))
	}

	err := os.MkdirAll(filepath.Dir(filePath), 0755)
	if err != nil {
		return nil, err
	}

	file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return nil, err
	}

	// 配置日志级别
	level := zap.NewAtomicLevel()
	level.SetLevel(zapcore.InfoLevel)

	// 配置编码器
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.RFC3339TimeEncoder
	encoder := zapcore.NewConsoleEncoder(encoderConfig)

	// 配置输出
	writer := zapcore.AddSync(file)
	core := zapcore.NewCore(encoder, writer, level)

	// 创建日志记录器
	logger := zap.New(core, zap.AddCaller())

	return logger, nil
}
